local rule = fk.CreateSkill{
    name = "#huan_1v1_rule&",
}

local U = require "packages/utility/utility"

--初始手牌
rule:addEffect(fk.DrawInitialCards, {
    can_refresh = function(self, event, target, player, data)
      return target == player and player:getMark("yuji1v1-ExtraHP") > 0
    end,
    on_refresh = function(self, event, target, player, data)
      data.num = 5
      player.room:setPlayerMark(player, "yuji1v1-ExtraHP", 0)
    end,
})

--先手第一回合少摸一张牌
rule:addEffect(fk.DrawNCards, {
  can_refresh = function(self, event, target, player, data)
    return target == player and player.seat == 1 and player.room:getBanner("1v1firstRound-lord") == 1
  end,
  on_refresh = function(self, event, target, player, data)
    data.n = data.n - 1
    player.room:setBanner("1v1firstRound-lord", 0)
  end,
})

--游戏结束判定
rule:addEffect(fk.GameOverJudge, {
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setTag("SkipGameRule", true)
    local other = player.next
    if other.rest > 0 then return end
    local ran_name = other.role == "lord" and "@&huan1V1-lordGenerals" or "@&huan1v1-nonlordGenerals" --跑掉武将
    local ran_generals = room:getBanner(ran_name) or  {}
    --胜负判定
    if table.find(ran_generals, function(p) return p == "huan_1v1__yuji" end) and (#ran_generals > 5) then
    room:gameOver(other.role)
    end
  end,
})


--阵亡重新选将
rule:addEffect(fk.BuryVictim, {
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setTag("SkipGameRule", true)
    player:bury()
    local other = player.next --击杀者
    if other.rest > 0 then return end
    local ran_name = other.role == "lord" and "@&huan1V1-lordGenerals" or "@&huan1v1-nonlordGenerals" --跑掉武将
    local ran_generals = room:getBanner(ran_name) or  {}
    if other:getMark("huan1v1-GeneralsNumber") == 1 then
      table.insert(ran_generals, other.general)
    else
      table.insert(ran_generals, other.general)
      if other.deputyGeneral ~= "blank_shibing" then
      table.insert(ran_generals, other.deputyGeneral)
      end
    end
    room:setBanner(ran_name, ran_generals)
    --移除你本小局的武将
    local exist_name = U.getPrivateMark(other, "&all_generals")
    local exist_bannner = other.role == "lord" and "@&lord_all_generals" or "@&nonlord_all_generals"
    local exist_generals = room:getBanner(exist_bannner) or {}
    if other:getMark("huan1v1-GeneralsNumber") == 1 then
      table.removeOne(exist_name, other.general)
      table.removeOne(exist_generals, other.general)
    else
      table.removeOne(exist_name, other.general)
      table.removeOne(exist_name, other.deputyGeneral)
      table.removeOne(exist_generals, other.general)
      table.removeOne(exist_generals, other.deputyGeneral)
    end
    U.setPrivateMark(other, "&all_generals", exist_name)
    room:setBanner(exist_bannner, exist_generals)
    --判定游戏是否结束
    if table.find(ran_generals, function(p) return p == "huan_1v1__yuji" end) and #ran_generals > 5 then
      room:gameOver(other.role)
    end
    other:throwAllCards("hej")
    --先保留一份标记，防止死亡的时候没了
    exist_bannner = player.role == "lord" and "@&lord_all_generals" or "@&nonlord_all_generals"
    local mark = room:getBanner(exist_bannner) or {}
    --重新给
    U.setPrivateMark(player, "&all_generals", mark)
    U.showPrivateMark(player, "&all_generals")

    room:revivePlayer(player, false)
    if other.dead then room:revivePlayer(other, false) end
    --下一小局开始，失败方选择先后手
    local choices = {"huan1v1-First", "huan1v1-Second"}
    local choice = room:askToChoice(player, {
      choices = choices,
      skill_name = "#huan1v1-select_seat",
    })
    if choice == "huan1v1-First" then
      room:sendLog{
        from = player.id,
        type = "#yuji1v1-first-select",
        toast = true,
      }
      room:setBanner("yuji1v1-first-select", 1)
    else
      room:sendLog{
        from = player.id,
        type = "#yuji1v1-second-select",
        toast = true,
      }
    end
    local n = room:getBanner("@huan1v1Counts")
    n = n + 1
    room:setBanner("@huan1v1Counts", n) --局数更新
    --双方重新选择武将
    room:sendLog{
      type = "当前为第 "..n.." 小局",
      toast = true,
    }
    --全部变士兵先，防止标记丢失
    for _, p in ipairs(room.players) do
      room:changeHero(p, "blank_shibing", true, true, false, false)
      room:changeHero(p, "blank_shibing", true, false, false, false)
    end
     --选择本小局上几个武将
     local req = Request:new(room.players, "AskForChoice")
     choices = {"huan1v1-One","huan1v1-Doubles"}
     req:setData(player, {choices, choices, "#huan1v1-SelectGeneral", "#huan1v1-SelectNumber"})
     req:setData(other, {choices, choices, "#huan1v1-SelectGeneral", "#huan1v1-SelectNumber"})
     req:setDefaultReply(player, "huan1v1-One")
     req:setDefaultReply(other, "huan1v1-One")

     req.focus_text = "#huan1v1-SelectNumber"
     req.receive_decode = false
     req:ask()

     for _, p in ipairs(room.players) do
      local result = req:getResult(p)
      if result == "huan1v1-One" then
         room:setPlayerMark(p, "huan1v1-GeneralsNumber", 1)
      else
         room:setPlayerMark(p, "huan1v1-GeneralsNumber", 2)
      end
    end

    --开始选将
    req = Request:new(room.players, "AskForGeneral")
    local mark1 = U.getPrivateMark(player, "&all_generals")
    local mark2 = U.getPrivateMark(other, "&all_generals")
    local x = player:getMark("huan1v1-GeneralsNumber")
    local y = other:getMark("huan1v1-GeneralsNumber")
    req:setData(player, { mark1, x })
    req:setData(other, { mark2, y })
    req:setDefaultReply(player, { mark1[1] })
    req:setDefaultReply(other, { mark2[1] })
    req:ask()

     --分配主副将
     for _, p in ipairs(room.players) do
      local main = req:getResult(p)[1]
      room:changeHero(p, main, true, false, true)
      room:setPlayerMark(p, "1v1_general", main)
      if p:getMark("huan1v1-GeneralsNumber") > 1 then
      local deputy = req:getResult(p)[2]
      room:changeHero(p, deputy, true, true, true)
      room:setPlayerMark(p, "1v1_deputy", deputy)
      end
      room:resumePlayerArea(p, {
        Player.WeaponSlot,
        Player.ArmorSlot,
        Player.OffensiveRideSlot,
        Player.DefensiveRideSlot,
        Player.TreasureSlot,
        Player.JudgeSlot,
      }) -- 全部恢复
    end

     --先手标记
     room:setBanner("1v1firstRound-lord", 1)
     room:askToChooseKingdom(room.players)
     --重新计算体力值(每小局选完将后都需要重新计算)
    for _, p in ipairs(room.players) do
    if p:getMark("huan1v1-GeneralsNumber") == 2 then --双将
       assert(p.general ~= "")
       local general = Fk.generals[p.general]
       local deputy = Fk.generals[p.deputyGeneral]
       local dmaxHp = deputy.maxHp
       local gmaxHp = general.maxHp
       p.maxHp = (dmaxHp + gmaxHp) // 2
       p.hp = p.maxHp
       p.shield = 0
       room:broadcastProperty(p, "general")
       room:broadcastProperty(p, "deputyGeneral")
       room:broadcastProperty(p, "maxHp")
       room:broadcastProperty(p, "hp")
       room:broadcastProperty(p, "shield")
       if (dmaxHp + gmaxHp) % 2 == 1 then
          room:setPlayerMark(p, "yuji1v1-ExtraHP", 1) --体力值余数标记，用于起始手牌+1
       end
     else
       assert(p.general ~= "")
       local general = Fk.generals[p.general]
       p.maxHp = general.maxHp
       p.hp = p.maxHp
       p.shield = 0
       room:broadcastProperty(p, "general")
       room:broadcastProperty(p, "maxHp")
       room:broadcastProperty(p, "hp")
       room:broadcastProperty(p, "shield")
     end
    end
    --重新分配牌堆和初始牌堆
    for _, p in ipairs(room.players) do
      if p:getMark("yuji1v1-ExtraHP") > 0 then
      p:drawCards(5, rule.name)
      room:setPlayerMark(p, "yuji1v1-ExtraHP", 0)
      else
      p:drawCards(4, rule.name)
      end
    end
    local current = room.current
    -- 1.自己选择先手且当前回合不是自己
    if room:getBanner("yuji1v1-first-select") ~= nil and current ~= player then
      room:setBanner("yuji1v1-first-select", 0)
      room:endTurn()
    --2.自己选择后手且当前回合不是自己
    elseif room:getBanner("yuji1v1-first-select") == nil and current ~= player then
      current:gainAnExtraTurn()
      room:endTurn()
    --3.自己选择先手且当前回合是自己
    elseif room:getBanner("yuji1v1-first-select") ~= nil and current == player then
      current:gainAnExtraTurn()
      room:endTurn()
      room:setBanner("yuji1v1-first-select", 0)
    --4.自己选择后手且当前回合是自己
    elseif room:getBanner("yuji1v1-first-select") == nil and current == player then
      room:endTurn()
    end
    --给登场留个位置（如果后面有的话）
  end,
})

return rule